const { DataTypes } = require('sequelize');

module.exports = (sequelize) => {
  const Order = sequelize.define('Order', {
  id: {
    type: DataTypes.BIGINT.UNSIGNED,
    primaryKey: true,
    autoIncrement: true
  },
  orderNumber: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  userId: {
    type: DataTypes.BIGINT.UNSIGNED,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  items: {
    type: DataTypes.JSON,
    allowNull: false
  },
  totalAmount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    comment: '总金额（保留字段，实际使用积分）'
  },
  discountAmount: {
    type: DataTypes.DECIMAL(10, 2),
    defaultValue: 0,
    comment: '折扣金额（保留字段，实际使用积分）'
  },
  finalAmount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    comment: '最终金额（保留字段，实际使用积分）'
  },
  pointsUsed: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  pointsEarned: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  status: {
    type: DataTypes.ENUM('pending', 'confirmed', 'processing', 'printing', 'completed', 'cancelled'),
    defaultValue: 'pending'
  },
  paymentStatus: {
    type: DataTypes.ENUM('unpaid', 'paid', 'refunded'),
    defaultValue: 'paid',
    comment: '支付状态（积分兑换默认为已支付）'
  },
  paymentMethod: {
    type: DataTypes.ENUM('points', 'wechat', 'alipay', 'cash'),
    allowNull: true,
    defaultValue: 'points',
    comment: '支付方式（默认为积分）'
  },
  deliveryInfo: {
    type: DataTypes.JSON,
    allowNull: true
  },
  estimatedCompletionTime: {
    type: DataTypes.DATE,
    allowNull: true
  },
  actualCompletionTime: {
    type: DataTypes.DATE,
    allowNull: true
  },
  notes: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  adminNotes: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  files: {
    type: DataTypes.JSON,
    allowNull: true
  }
}, {
  tableName: 'orders',
  timestamps: true
});

  // 生成订单号的钩子
  Order.beforeCreate(async (order) => {
    if (!order.orderNumber) {
      const date = new Date();
      const dateStr = date.getFullYear().toString() + 
                     (date.getMonth() + 1).toString().padStart(2, '0') + 
                     date.getDate().toString().padStart(2, '0');
      const randomStr = Math.random().toString(36).substr(2, 6).toUpperCase();
      order.orderNumber = `ORD${dateStr}${randomStr}`;
    }
  });

  // 备用方案：如果钩子失败，在验证前再次检查
  Order.beforeValidate(async (order) => {
    if (!order.orderNumber) {
      const date = new Date();
      const dateStr = date.getFullYear().toString() + 
                     (date.getMonth() + 1).toString().padStart(2, '0') + 
                     date.getDate().toString().padStart(2, '0');
      const randomStr = Math.random().toString(36).substr(2, 6).toUpperCase();
      order.orderNumber = `ORD${dateStr}${randomStr}`;
    }
  });

  // 关联关系
  Order.associate = (models) => {
    Order.belongsTo(models.User, {
      foreignKey: 'userId',
      as: 'User'
    });
    
    Order.hasMany(models.OrderItem, {
      foreignKey: 'orderId',
      as: 'orderItems'
    });
  };

  return Order;
};